package pay.portal;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import pay.portal.web.message.TransferOrderMsg;
import pay.service.IOrderHelper;
import pay.service.IOrderJpa;
import pay.service.ITransfer;
import pay.utils.JsonUtils;

/**
 * 
 * 产品起标后将相关信息写入 交易记录表trade Info中
 * 
 * @author 华康
 *
 */
@Component
public class ProdStartMarkScheduler {
	protected Logger logger = LoggerFactory
			.getLogger(this.getClass().getName());
	
	@Autowired
	private IOrderHelper orderHelperService;
	
	@Autowired
	private IOrderJpa orderJpaService;
	
	@Autowired
	private ITransfer transferService;
	
	
	// 每隔1分钟执行一次
	@Scheduled(cron = "0 0/1 * * * ?")
	public void testTasks() {
		logger.info("查询标是否成立定时任务开始 ProductCreateScheduler ……");
		ExecutorService executor = Executors.newFixedThreadPool(1);
		Runnable task = new Runnable() {
			public void run() {
				prodStartMarkTask();
			}
		};
		executor.execute(task);
		executor.shutdown();
		logger.info("查询标是否成立定时任务结束 ProductCreateScheduler ……");
	}

	/**
	 * 产品起标之后，将钱从客户金账户中划转到债权人的金账户中，并更新订单的相关属性
	 *
	 */
	private void prodStartMarkTask() {
		List<String> transferOrderList = orderHelperService.getTranseferOrderListFromRedis();
		
		if (transferOrderList != null &&  transferOrderList.size() > 0){
			logger.info("标成立，开始进行划拨， 待划拨的记录总数是： size ={}", transferOrderList.size());
		}else{
			logger.info("标成立，开始进行划拨， 待划拨的记录总数是：0,操作停止");
			return ;
		}
		
		for(String transferMsgStr: transferOrderList ){
			
			TransferOrderMsg transferOrderMsg = JsonUtils.toBean(transferMsgStr, TransferOrderMsg.class);
			
			Long orderId = transferOrderMsg.getOrderId();
			
			String mchnt_txn_ssn = transferService.getSSN(orderId);
			
			//将需要进行划拨的记录放入redis中
			transferService.addTransferRecordIntoRedis(mchnt_txn_ssn, transferMsgStr);
			
			//进行划拨操作
			Boolean result = transferService.transfer(mchnt_txn_ssn);
			
			logger.info("划拨结果是 result={}, orderId={}", result,
					transferOrderMsg.getOrderId());
		}	
		 
	}
}
